//
//  RockClimbingDataModel.swift
//  TimeBoat
//
//  Created by Jun on 2022/9/8.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import Foundation

/// 攀岩
@objcMembers class RockClimbingDataModel: NSObject {
    /// 高度 2Byte (单位:米)
    var height: UInt16 = 0

    /// 所用时间 4Byte (单位:秒)
    var useTime: UInt32 = 0

    /// 心率数组 uint8[] (单位:次/分钟，每分钟记录一次数据)
    var heartRateList: [UInt8]? = nil

    /// 卡路里 4Byte (单位：卡)
    var calorie: UInt32 = 0

    ///  海拔高度数组 int16 [
    var altitudeList: [UInt16]? = nil
    
    convenience init(buf: [UInt8]) {
        self.init()
        
        var index = 0
        
        if (index + 2 <= buf.count) {
            //高度 2Byte (单位:米)
            height = UInt16.toUInt16(buf: buf, offset: index)
            index += 2
        }

        if (index + 4 <= buf.count) {
            // 所用时间 4Byte (单位:秒)
            useTime = UInt32.toUInt32(buf: buf, offset: index)
            index += 4
        }

        if (index + 2 <= buf.count) {
            // 心率数组 uint8[] (单位:次/分钟，每分钟记录一次数据)
            let heartRateArrayLength = Int(UInt16.toUInt16(buf: buf, offset: index))
            index += 2

            if (heartRateArrayLength > 0) {
                if (index + heartRateArrayLength <= buf.count) {
                    heartRateList = Array<UInt8>.copyBuffer(buffer: buf, offset: index, length: heartRateArrayLength)
                    index += heartRateArrayLength
                } else {
                    Log.debug("index + heartRateArrayLength * 2 is overflow, \(index), \(heartRateArrayLength)")
                }
            }
        }

        if (index + 4 <= buf.count) {
            //卡路里 4Byte (单位：卡)
            calorie = UInt32.toUInt32(buf: buf, offset: index)
            index += 4
        }

        if (index + 2 <= buf.count) {
            // 海拔高度数组 int16 []
            // 海拔高度数组 单位:秒, 每公里所用时间，每公里记录一次数据
            let altitudeLength = Int(UInt16.toUInt16(buf: buf, offset: index))
            index += 2

            if (altitudeLength > 0) {
                if (index + altitudeLength * 2 <= buf.count) {
                    altitudeList = [UInt16]()
                    for _ in 0...(altitudeLength-1) {
                        let data = UInt16.toUInt16(buf: buf, offset: index)
                        index += 2

                        altitudeList?.append(data)
                    }
                } else {
                    Log.debug("index + altitudeLength * 2 is overflow, \(index), \(altitudeLength)")
                }
            }
        }
    }
    
    @objc func toString() -> String {
        var str = self.yy_modelToJSONString()
        if nil == str {
            str = ""
        }
        
        return str!
    }
}
